import 'dart:io';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// 选择类型枚举
enum PickerType {
  imageOnly, // 仅图片
  videoOnly, // 仅视频
  imageAndVideo, // 图片和视频
}

/// 选择结果
class ImagePickerResult {
  final List<File> images;
  final List<File> videos;

  ImagePickerResult({required this.images, required this.videos});

  bool get hasData => images.isNotEmpty || videos.isNotEmpty;
}

/// 图片选择配置
class ImagePickerConfig {
  final PickerType pickerType;
  final int maxImages;
  final int maxVideos;

  const ImagePickerConfig({
    this.pickerType = PickerType.imageOnly,
    this.maxImages = 1,
    this.maxVideos = 1,
  });
}

/// 图片选择器 Notifier
class ImagePickerNotifier extends Notifier<ImagePickerResult?> {
  static const int _maxVideoDurationSeconds = 30;

  @override
  ImagePickerResult? build() {
    return null;
  }

  /// 从相册选择
  Future<ImagePickerResult?> pickFromGallery({
    required BuildContext context,
    required ImagePickerConfig config,
  }) async {
    try {
      // 请求权限
      final hasPermission = await _requestPermission(context);
      if (!hasPermission) {
        return null;
      }

      // 根据配置类型确定 RequestType
      RequestType? requestType;
      if (config.pickerType == PickerType.imageOnly) {
        requestType = RequestType.image;
      } else if (config.pickerType == PickerType.videoOnly) {
        requestType = RequestType.video;
      } else {
        requestType = RequestType.all;
      }

      // 计算最大可选数量
      final maxAssets = _calculateMaxAssets(config);

      // 当允许同时选择图片和视频时，启用微信朋友圈模式：仅允许 单视频 或 多图片，禁止混选。
      // 注意：wechatMoment 要求 requestType 为 RequestType.common。
      final bool useWechatMoment = requestType == RequestType.all;
      final pickerConfig = AssetPickerConfig(
        maxAssets: useWechatMoment ? (maxAssets.clamp(1, 9)) : maxAssets,
        selectedAssets: const [],
        requestType: useWechatMoment ? RequestType.common : requestType,
        specialPickerType: useWechatMoment
            ? SpecialPickerType.wechatMoment
            : null,
        textDelegate: const AssetPickerTextDelegate(),
      );

      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: pickerConfig,
      );

      if (result == null || result.isEmpty) {
        return null;
      }

      // 处理选中的资源
      return await _processAssets(result, config);
    } catch (e, stackTrace) {
      Log.e('选择图片/视频失败', e, stackTrace);
      return null;
    }
  }

  /// 请求权限
  Future<bool> _requestPermission(BuildContext context) async {
    try {
      // 使用 PhotoManager 请求权限（wechat_assets_picker 依赖 photo_manager）
      final PermissionState photoStatus =
          await PhotoManager.requestPermissionExtend();

      // 检查权限状态
      if (photoStatus == PermissionState.denied) {
        if (context.mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('需要相册权限才能选择图片，请在设置中开启')));
        }
        return false;
      }

      if (photoStatus == PermissionState.restricted) {
        // 权限被限制（iOS），提示用户去设置中开启
        if (context.mounted) {
          final shouldOpen = await showDialog<bool>(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('需要相册权限'),
              content: const Text('请在设置中开启相册权限，以便选择图片或视频'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('去设置'),
                ),
              ],
            ),
          );

          if (shouldOpen == true) {
            await openAppSettings();
          }
        }
        return false;
      }

      if (!photoStatus.isAuth) {
        // 其他未授权状态
        if (context.mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('需要相册权限才能选择图片或视频')));
        }
        return false;
      }

      return true;
    } catch (e) {
      Log.e('请求权限失败', e, StackTrace.current);
      return false;
    }
  }

  /// 计算最大可选数量
  int _calculateMaxAssets(ImagePickerConfig config) {
    if (config.pickerType == PickerType.imageOnly) {
      return config.maxImages;
    } else if (config.pickerType == PickerType.videoOnly) {
      return config.maxVideos;
    } else {
      // 图片和视频时，取两者之和
      return config.maxImages + config.maxVideos;
    }
  }

  /// 处理选中的资源
  Future<ImagePickerResult> _processAssets(
    List<AssetEntity> assets,
    ImagePickerConfig config,
  ) async {
    final List<File> images = [];
    final List<File> videos = [];
    bool hasInvalidVideo = false;

    for (final asset in assets) {
      final file = await asset.file;
      if (file != null) {
        if (asset.type == AssetType.image) {
          // 检查图片数量限制
          if (images.length < config.maxImages) {
            images.add(file);
          }
        } else if (asset.type == AssetType.video) {
          if (asset.duration > _maxVideoDurationSeconds) {
            hasInvalidVideo = true;
            continue;
          }
          // 检查视频数量限制
          if (videos.length < config.maxVideos) {
            videos.add(file);
          }
        }
      }
    }

    if (hasInvalidVideo) {
      ToastUtil.show('仅支持30秒以内的视频');
    }

    final result = ImagePickerResult(images: images, videos: videos);
    state = result;
    return result;
  }

  /// 清除选择结果
  void clear() {
    state = null;
  }
}

/// Provider
final imagePickerNotifierProvider =
    NotifierProvider<ImagePickerNotifier, ImagePickerResult?>(
      () => ImagePickerNotifier(),
    );
